package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.advice.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
//import com.sun.tools.javac.util.StringUtils;
import enums.ExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;


    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        PageHelper.startPage(page,rows);
        Example example = new Example(Brand.class);
        if (!StringUtils.isEmpty(key)) {
            // 排序
            example.createCriteria().andLike("name","%"+ key+"%").orEqualTo("name",key);

        }

        if (!StringUtils.isEmpty(sortBy)){
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }

        //查询
        Page<Brand> pageInfo = (Page<Brand>)brandMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(pageInfo)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }


        return new PageResult<Brand>(pageInfo.getTotal(),pageInfo.getResult());
    }

    /**
     * 新增品牌
     * */

    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        brand.setId(null);
        int count =    brandMapper.insert(brand);
        if (count !=1){
            throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);
        }

        //新增中间表.

        for (Long cid :cids){
          count =  brandMapper.insertCategoryByBrand(cid,brand.getId());
          if (count != 1){
              throw new LyException(ExceptionEnum.BRAND_SAVE_ERROR);
          }
        }
    }

    public Brand queryById(Long id){
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brand;
    }

    public List<Brand> queryByCid(Long cid) {
        List<Brand> brands = brandMapper.queryByCategoryId(cid);
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return brands;
    }
}
